# -*- coding: utf-8 -*-

import time
import logging
import threading
#####################
import utility
from json_message_processor import JsonMessageProcessor
import message_types_res as message_types
import datetime

from pybus import bus_singleton
import app_common as app_com

HEADER_LENGTH = 16

class MessageHandler:
    def __init__(self, cmd_queue, conf, types, client):
        logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',\
            level=logging.DEBUG)
        self.conf = conf
        self.msg_types = types
        self.client = client
        self.json_praser = JsonMessageProcessor()
        self.cmd_queue = cmd_queue
        
        # 设置状态和心跳定时器
        self.status_timer = utility.RepeatedTimer(6, self.send_status_ntf)
        heartbeat_interval = int(self.conf["heartbeat_interval"]) or 10
        self.heartbeat_timer = utility.RepeatedTimer(heartbeat_interval, self.send_heartbeat_req)
        
        # 设置消息回调注册
        bus_singleton.subscribe(app_com.kMsgTcpClose, self, self.doTcpClosed)
        bus_singleton.subscribe(app_com.kMsgTcpConnected, self, self.doTcpConnected)

    def start(self):
        self.cmd_thread = threading.Thread(target=self.recv_cmd_handle)
        self.cmd_thread.setDaemon(True)
        self.cmd_thread.start()
    
    def doTcpClosed(self):
        '''
        tcp连接断开后的回调函数
        '''
        if self.status_timer.is_running:
            self.status_timer.stop()
        if self.heartbeat_timer.is_running:
            self.heartbeat_timer.stop()
    
    def doTcpConnected(self):
        '''
        建立tcp连接成功后的回调函数
        '''
        self.send_login_req()
    
    def recv_cmd_handle(self):
        while True:
            cmd = self.cmd_queue.get()
            if cmd is None:
                continue
            if cmd["type"] == self.msg_types[message_types.kLoginRsp]:
                # logging.info("recv login rsp")
                ret = self.json_praser.decode_login_rsp(cmd["body"])
                if ret != 1000 and ret != "1000":
                    logging.error("login rsp error %s", ret)
                    time.sleep(int(self.conf["reconnect_interval"]))
                else:
                    if not self.status_timer.is_running:
                        self.status_timer.start()
                    if not self.heartbeat_timer.is_running:
                        self.heartbeat_timer.start()
            
            elif cmd["type"] == self.msg_types[message_types.kHeartRsp]:
                logging.info("recv heartbeat rsp")
                ret = self.json_praser.decode_heart_rsp(cmd["body"])
                if ret != 1000 and ret != "1000":
                    logging.error("heartbeat rsp error %s", ret)
                else:
                    pass
            else:
                logging.debug("recv other type") 

    def send_login_req(self):
        data = {}
        msg = {}
        msg["body"] = self.json_praser.encode_login_req(data)
        msg["type"] = self.msg_types[message_types.kLoginReq]

        self.client.send_to_queue(msg)
        logging.debug("send login message")

    
    def send_heartbeat_req(self):
        data = {}
        msg = {}
        msg["body"] = self.json_praser.encode_heartbeat_req(data)
        msg["type"] = self.msg_types[message_types.kHeartReq]

        self.client.send_to_queue(msg)
        logging.info("send heartbeat message")

    def send_status_ntf(self):
        data = {}
        data["status"] = "1000"
        msg = {}
        msg["body"] = self.json_praser.encode_status_ntf(data)
        msg["type"] = self.msg_types[message_types.kStatusNtf]
        
        self.client.send_to_queue(msg)


